package com.democaffien.demos.controller;

import com.democaffien.demos.entity.User;
import com.democaffien.demos.service.UserService;
import com.github.benmanes.caffeine.cache.Cache;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author rise
 * @date 2024年10月30日 16:14
 */
@RestController
@RequestMapping("/userApi")
public class UserControllerUseCaffeineAPI {
    @Resource
    private UserService userService;
    @Resource
    private Cache<String, Object> caffeineCache;


    @PostMapping("add")
    public User add(@RequestBody User user){
        //这里是将插入数据的结果写入到缓存中，
        User add = userService.add(user);
        caffeineCache.put("user::"+add.getId(),add);
        return add;
    }
    @GetMapping("/{id}")
    public User get(@PathVariable Integer id){
       return (User)caffeineCache.get("user::"+id,item->userService.getById(id));
    }

    @DeleteMapping("/{id}")
    public Integer delete(@PathVariable Integer id){
         caffeineCache.invalidate("user::"+id);
        return userService.delete(id);
    }

    @DeleteMapping("all")
    public Integer deleteAll(){
        caffeineCache.invalidateAll();
        return userService.deleteAll();
    }
}
